<template>
    <div class="building-manage">
        <!-- 统计概览 -->
        <!--        <el-row :gutter="20" class="stats-row">
                <el-col :xs="24" :sm="12" :md="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon buildings">
                                <el-icon :size="40"><OfficeBuilding /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.totalBuildings }}</div>
                                <div class="stat-label">楼栋总数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon rooms">
                                <el-icon :size="40"><School /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.totalRooms }}</div>
                                <div class="stat-label">宿舍总数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon capacity">
                                <el-icon :size="40"><UserFilled /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.totalCapacity }}</div>
                                <div class="stat-label">总容纳人数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon rate">
                                <el-icon :size="40"><TrendCharts /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.avgOccupancyRate }}%</div>
                                <div class="stat-label">平均入住率</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>-->

        <!-- 表格区域 -->
        <el-card shadow="hover" class="table-card">
            <template #header>
                <div class="card-header">
                    <span class="title">楼栋列表</span>
                    <div class="header-actions">
                        <el-button 
                            type="danger" 
                            plain 
                            @click="handleBatchDelete" 
                            :disabled="selectedRows.length === 0"
                        >
                            <el-icon>
                                <Delete />
                            </el-icon>
                            批量删除 ({{ selectedRows.length }})
                        </el-button>
                        <el-button type="primary" @click="handleAdd">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            添加楼栋
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 搜索区域 -->
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="楼栋名称">
                    <el-input
                        v-model="searchForm.buildingName"
                        placeholder="请输入楼栋名称"
                        clearable
                        style="width: 200px"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button @click="handleReset">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>

            <!-- 表格 -->
            <el-table
                :data="tableData"
                style="width: 100%"
                v-loading="loading"
                border
                max-height="calc(100vh - 350px)"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="buildingName" label="楼栋名称" width="120" />
                <el-table-column prop="floors" label="楼层数" width="100" />
                <el-table-column prop="totalRooms" label="宿舍总数" width="120" />
                <el-table-column prop="capacity" label="容纳人数" width="120" />
                <el-table-column prop="occupied" label="已入住" width="100" />
                <el-table-column label="空余床位" width="120">
                    <template #default="scope">
                        {{ scope.row.capacity - scope.row.occupied }}
                    </template>
                </el-table-column>
                <el-table-column label="入住率" width="150">
                    <template #default="scope">
                        <el-progress
                            :percentage="scope.row.occupancyRate"
                            :color="getProgressColor(scope.row.occupancyRate)"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.occupancyRate)">
                            {{ getStatusText(scope.row.occupancyRate) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" text @click="handleEdit(scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" text @click="handleDelete(scope.row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </el-card>

        <!-- 添加/编辑楼栋弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="700px"
            :close-on-click-modal="false"
            @close="handleDialogClose"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="120px"
                class="building-form"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="楼栋名称" prop="buildingName">
                            <el-input
                                v-model="form.buildingName"
                                placeholder="请输入楼栋名称"
                                :disabled="isEdit"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="楼层数" prop="floors">
                            <el-input-number
                                v-model="form.floors"
                                :min="1"
                                :max="50"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="宿舍总数" prop="totalRooms">
                            <el-input-number
                                v-model="form.totalRooms"
                                :min="1"
                                :max="1000"
                                style="width: 100%"
                                @change="handleRoomsChange"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="容纳人数" prop="capacity">
                            <el-input-number
                                v-model="form.capacity"
                                :min="1"
                                :max="10000"
                                style="width: 100%"
                                @change="handleCapacityChange"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="已入住" prop="occupied">
                            <el-input-number
                                v-model="form.occupied"
                                :min="0"
                                :max="form.capacity"
                                style="width: 100%"
                                @change="calculateOccupancyRate"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入住率">
                            <el-input
                                :model-value="form.occupancyRate + '%'"
                                disabled
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="主题颜色" prop="color">
                    <el-color-picker v-model="form.color" />
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入备注信息"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Plus,
    OfficeBuilding,
    School,
    UserFilled,
    TrendCharts,
    Search,
    Refresh,
    Edit,
    Delete,
} from '@element-plus/icons-vue'
import { getBuildingList, addBuilding, updateBuilding, deleteBuilding, batchDeleteBuildings } from '@/api/building'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = ref({
    buildingName: '',
})

const tableData = ref([])
const selectedRows = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const currentEditIndex = ref(-1)

const dialogTitle = computed(() => {
    return isEdit.value ? '编辑楼栋' : '添加楼栋'
})

const form = ref({
    buildingName: '',
    floors: 6,
    totalRooms: 100,
    capacity: 500,
    occupied: 0,
    occupancyRate: 0,
    color: '#409EFF',
    remark: '',
})

const rules = {
    buildingName: [{ required: true, message: '请输入楼栋名称', trigger: 'blur' }],
    floors: [{ required: true, message: '请输入楼层数', trigger: 'blur' }],
    totalRooms: [{ required: true, message: '请输入宿舍总数', trigger: 'blur' }],
    capacity: [{ required: true, message: '请输入容纳人数', trigger: 'blur' }],
    occupied: [{ required: true, message: '请输入已入住人数', trigger: 'blur' }],
    color: [{ required: true, message: '请选择主题颜色', trigger: 'change' }],
}

// 统计数据
const stats = computed(() => {
    const totalBuildings = tableData.value.length
    const totalRooms = tableData.value.reduce((sum, b) => sum + b.totalRooms, 0)
    const totalCapacity = tableData.value.reduce((sum, b) => sum + b.capacity, 0)
    const avgOccupancyRate = Math.round(
        tableData.value.reduce((sum, b) => sum + b.occupancyRate, 0) / totalBuildings,
    )

    return {
        totalBuildings,
        totalRooms,
        totalCapacity,
        avgOccupancyRate,
    }
})

// 重置表单
const resetForm = () => {
    form.value = {
        buildingName: '',
        floors: 6,
        totalRooms: 100,
        capacity: 500,
        occupied: 0,
        occupancyRate: 0,
        color: '#409EFF',
        remark: '',
    }
}

// 计算入住率
const calculateOccupancyRate = () => {
    if (form.value.capacity > 0) {
        form.value.occupancyRate = Math.round((form.value.occupied / form.value.capacity) * 100)
    } else {
        form.value.occupancyRate = 0
    }
}

// 宿舍总数改变
const handleRoomsChange = () => {
    // 可以添加根据宿舍数自动计算容纳人数的逻辑
    // 例如：每间宿舍4人
    // form.value.capacity = form.value.totalRooms * 4
    calculateOccupancyRate()
}

// 容纳人数改变
const handleCapacityChange = () => {
    if (form.value.occupied > form.value.capacity) {
        form.value.occupied = form.value.capacity
    }
    calculateOccupancyRate()
}

// 获取楼栋列表
const fetchBuildingList = async () => {
    loading.value = true
    try {
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value,
            ...searchForm.value,
        }
        const res = await getBuildingList(params)
        if (res.code === 200 || res.code === 0) {
            tableData.value = res.data.list || res.data
            total.value = res.data.total || 0
        }
    } catch (error) {
        console.error('获取楼栋列表失败:', error)
        tableData.value = [
            {
                id: 1,
                buildingName: 'A栋',
                color: '#409EFF',
                floors: 6,
                totalRooms: 48,
                capacity: 192,
                occupied: 180,
                occupancyRate: 94,
                remark: '标准学生宿舍楼',
            },
            {
                id: 2,
                buildingName: 'B栋',
                color: '#67C23A',
                floors: 6,
                totalRooms: 48,
                capacity: 192,
                occupied: 175,
                occupancyRate: 91,
                remark: '配备电梯的现代化宿舍楼',
            },
        ]
        total.value = tableData.value.length
    } finally {
        loading.value = false
    }
}

// 添加楼栋
const handleAdd = () => {
    resetForm()
    isEdit.value = false
    dialogVisible.value = true
}

// 编辑楼栋
const handleEdit = (row) => {
    isEdit.value = true
    currentEditIndex.value = row.id
    form.value = { ...row }
    dialogVisible.value = true
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 批量删除楼栋
const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 个楼栋吗？删除后将无法恢复！`,
            '批量删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: true
            }
        )

        const ids = selectedRows.value.map(row => row.id)
        const res = await batchDeleteBuildings(ids)

        if (res.code === 200 || res.code === 0) {
            ElMessage.success(res.message || `批量删除成功，共删除 ${ids.length} 条数据`)
            selectedRows.value = []
            fetchBuildingList()
        } else {
            ElMessage.error(res.message || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
            console.error('批量删除楼栋失败:', error)
            ElMessage.error(error.message || '批量删除失败')
        }
    }
}

// 删除楼栋
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除楼栋 ${row.buildingName} 吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })

        const res = await deleteBuilding(row.id)
        if (res.code === 200 || res.code === 0) {
            ElMessage.success('删除成功')
            fetchBuildingList()
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除楼栋失败:', error)
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                if (isEdit.value) {
                    const res = await updateBuilding(currentEditIndex.value, form.value)
                    if (res.code === 200 || res.code === 0) {
                        ElMessage.success('修改成功')
                        dialogVisible.value = false
                        fetchBuildingList()
                    }
                } else {
                    const res = await addBuilding(form.value)
                    if (res.code === 200 || res.code === 0) {
                        ElMessage.success('添加成功')
                        dialogVisible.value = false
                        fetchBuildingList()
                    }
                }
            } catch (error) {
                console.error('提交失败:', error)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 弹窗关闭时重置表单
const handleDialogClose = () => {
    formRef.value?.resetFields()
    resetForm()
    currentEditIndex.value = -1
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchBuildingList()
}

// 重置搜索
const handleReset = () => {
    searchForm.value = {
        buildingName: '',
    }
    handleSearch()
}

// 分页
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchBuildingList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchBuildingList()
}

// 初始化
onMounted(() => {
    fetchBuildingList()
})

// 进度条颜色
const getProgressColor = (rate) => {
    if (rate >= 90) return '#f56c6c'
    if (rate >= 70) return '#e6a23c'
    return '#67c23a'
}

// 状态类型
const getStatusType = (rate) => {
    if (rate >= 90) return 'danger'
    if (rate >= 70) return 'warning'
    return 'success'
}

// 状态文本
const getStatusText = (rate) => {
    if (rate >= 90) return '紧张'
    if (rate >= 70) return '适中'
    return '充足'
}
</script>

<style lang="scss" scoped>
.building-manage {
    /*.stats-row {
      margin-bottom: 20px;

      .stat-card {
          margin-bottom: 20px;

          :deep(.el-card__body) {
              padding: 20px;
          }

          .stat-content {
              display: flex;
              align-items: center;
              gap: 20px;

              .stat-icon {
                  width: 70px;
                  height: 70px;
                  border-radius: 12px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  color: #fff;

                  &.buildings {
                      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                  }

                  &.rooms {
                      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                  }

                  &.capacity {
                      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                  }

                  &.rate {
                      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
                  }
              }

              .stat-info {
                  flex: 1;

                  .stat-number {
                      font-size: 28px;
                      font-weight: 600;
                      color: #333;
                      margin-bottom: 5px;
                  }

                  .stat-label {
                      font-size: 14px;
                      color: #666;
                  }
              }
          }

          &:hover {
              transform: translateY(-5px);
              transition: all 0.3s;
          }
      }
  }*/

    .table-card {
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .title {
                font-size: 18px;
                font-weight: 600;
                color: #333;
            }
        }

        .search-form {
            margin-bottom: 20px;
        }

        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
        }
    }

    .building-form {
        padding: 20px 20px 0;

        :deep(.el-input-number) {
            width: 100%;
        }

        :deep(.el-color-picker) {
            width: 100%;
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
}
</style>
